clear all
set more off
cap log close

********************************************************************************
***** Project: The Short and Long Term Effects of In-Person Performance Feedback
********************************************************************************
***** A. R. Soetevent & G. J. Romensen
********************************************************************************
***** Basic regressions - Coaching - Robustness check that correct for rush hours
********************************************************************************
********************************************************************************
*global filepath "C:\JPEMicReplication"
*global paperpath "$filepath\TablesGraphs"

local abcd "acceleratie rem bochten fueleconomyLpKM"
log using "$filepath/Logs/X03RegressionsCoachingRobustRushFR.log", replace

/*** Notes ***/
*=> No fuel economy observations postfeedback in urban area.
*=> Fuel Economy: kilometers per liter of fuel
*=> ABC dimensions: number of events per 10 kilometers
/*************/

use "$filepath\ConstructedData\DataMainAnalysisDEPO.dta"

rename bustype bustypes
** Drop all Irisbus observations
drop if bustypes==3
gen byte ZH = 0 
replace ZH = 1 if regio == "ZH"

** Analysis: based on Treatment region
drop if regio == "ZH"

replace intouro = 0 if intouro ==.

* Drop months with imperfect tracking by coaches 
drop if datum>date("30-4-2016", "DMY")

* Drop eco-coaches [chauf_nr_rug: randomly generated depository numbers!]
local eco_nr "939 1404 519 1286 1610 531"

foreach x of local eco_nr {
drop if chauf_nr_rug==`x'
}

** Newly defined variables [geplande_ritafstand is in meters, for this reason *1000]
gen aantal_haltespKM = (1000*aantal_haltes)/geplande_ritafstand
label variable aantal_haltespKM "Nr. stops per km."

/*** Determine the set of observations used for the analysis ***/
gen byte regobsfuel=1
replace regobsfuel=0 if geplande_ritafstand==. | lnovcheckins==. | punctuality==. | aantal_haltes==. | dep_fueleconomyLpKM==.

gen byte regobsabc=1
replace regobsabc=0  if geplande_ritafstand==. | lnovcheckins==. | punctuality==. | aantal_haltes==. | dep_acceleratie==. | dep_bochten==. | dep_rem==.



****************************************
*** A. Create global list of covariates
****************************************
global covMaand "maand_1 maand_2 maand_3 maand_4 maand_6 maand_7 maand_8 maand_9 maand_10 maand_11 maand_12" 
* (May = default)

global covBusType "vdl10 vdl14 iris10 iris10cng iris12 iris12cng intouro"
* (vdl12 = default - more than 50 per cent of observations)

global covWeather "Temp6_3C Temp3_0C Temp0_3C Temp3_6C Temp9_12C Temp12_15C Temp15_18C Temp18_21C Temp21_24C Temp24_27C Rain5_10mm Rain10_15mm Rain15_20mm Rain20_30mm Rain30_40mm Wind0_2ms Wind4_6ms Wind6_8ms Wind8_10ms Wind10_20ms"  
*(Defaults: Wind2_4ms, Temp6_9C, Rain0_5mm)

*** THIS IS THE ONLY AND KEY CHANGE COMPARED TO BASE COACHING REGRESSSIONS: RUSH HOUR DUMMIES ARE LEFT OUT OF LIST EXPLANATORY VARIABLES
*global covEnvironm "ochtendspits avondspits uitleenrit geplande_ritafstand aantal_haltespKM stadsrit"
global covEnvironm "uitleenrit geplande_ritafstand aantal_haltespKM stadsrit"

global covPassengers "lnovcheckins ovcheckinsmissing"

global covEndogenous "punctuality"

** Postcoaching dummies: non treatment-specific
global  covPostCoaching
	foreach x of numlist 0(7)70 {
		global covPostCoaching "$covPostCoaching daysaftercoachingA`x'" 
	}
	global covPostCoaching "$covPostCoaching daysaftercoachingA70plus"

	** Postcoaching dummies: treatment-specific
global  covPostCoachingT
foreach i of numlist 1(1)4 {
	foreach x of numlist 0(7)70 {
		global covPostCoachingT "$covPostCoachingT daysaftercoaching`x'T`i'" 
	}
	global covPostCoachingT "$covPostCoachingT daysaftercoaching70T`i'plus"
}

** Precoaching dummies: non treatment-specific
global covPreCoaching
global covPreCoaching "$covPreCoaching daysbeforecoachingA70min"
	foreach x of numlist 70(7)14 {
		global covPreCoaching "$covPreCoaching daysbeforecoachingA`x'" 
	}
	
set matsize 10000

*************************************
** Estimation effect coaching + plots
*************************************
xtset chauf_nr_rug 
**************************************************************************************************************************************************************
***  [Table N.16: Dynamic Treatment Effects In-Person Coaching on Driving Performance – Rush Hours Excluded as Control Variable ]
**************************************************************************************************************************************************************

** REGRESSIONS **
gen byte selectie=0
local i = 0
foreach var of local abcd {
	local i = `i' + 1
		if `i'<4 {
		replace selectie=regobsabc 
		}
		if `i'==4 {
		replace selectie=regobsfuel 
		}
	if `i'==1 { 
		local ynaam  "Change in number of events per 10km" 
		local yschaal "r(-2 .2)" 
		local ylabeltje "-2 -1.5 -1 -0.5 0"
	}
	else if `i'==2 { 
			local ynaam  "Change in number of events per 10km" 
		local yschaal "r(-0.2 0.2)" 
		local ylabeltje "-0.2 -0.1 0 0.1 0.2"
	}
	else if `i'==3 { 
		local ynaam  "Change in number of events per 10km" 
		local yschaal "r(-0.2 0.2)" 
		local ylabeltje "-0.2 -0.1 -0.0 0.1 0.2"
	}
	else if `i'==4 { 
		local ynaam  "Change in fuel economy (liters/100km)" 
		local yschaal "r(-0.8 0.2)" 
		local ylabeltje "-0.8 -0.6 -0.4 -0.2 0 0.2"
	}
	
* (1) FE - without controls + day and bustype fixed effects (including interactions)
di "`var'"
xtreg dep_`var' postcoaching i.datum if selectie==1, fe cluster(chauf_nr_rug)
estadd loc controls "No", replace
estadd loc driverfe "No", replace
estadd loc dayfe 	"Yes", replace	
estadd loc busdayfe "No", replace 
estimates store m`var'1,  title(m`var'1)
* (2) FE + controls + day and bustype fixed effects (including interactions)
xtreg dep_`var' postcoaching  $covBusType $covPassengers $covEnvironm  i.bustypes i.datum i.bustypes#i.datum if selectie==1, fe cluster(chauf_nr_rug)
estadd loc controls "Yes", replace
estadd loc driverfe "Yes", replace
estadd loc dayfe 	"Yes", replace	
estadd loc busdayfe "Yes", replace 
estimates store m`var'2,  title(m`var'2)
* (3) FE + day and bustype fixed effects (including interactions) - Non treatment specific impact coaching
xtreg dep_`var' $covPreCoaching $covPostCoaching $covBusType $covPassengers $covEnvironm  i.bustypes i.datum i.bustypes#i.datum if selectie==1, fe cluster(chauf_nr_rug)
estadd loc controls "Yes", replace
estadd loc driverfe "Yes", replace
estadd loc dayfe 	"Yes", replace	
estadd loc busdayfe "Yes", replace 
estimates store m`var'3,  title(m`var'3)

 * Test lags = 0
test $covPreCoaching 
 * Test leads = 0
test $covPostCoaching 

*****************************************************************************
***  [Figure XX: Dynamic Treatment Effects of In-Person Coaching [TWFE]]
*****************************************************************************
coefplot (m`var'3), keep(daysbefore* daysafter*) drop(daysafter*plus daysbefore*min) vertical yline(0) xlabel("") xtick(#20)  xlabel(1 "-10" 2 "-9" 3 "-8" 4 "-7" 5 "-6" 6 "-5" 7 "-4"  8 "-3"  9 "-2" 10 "0" 11 "1" 12 "2" 13 "3" 14 "4" 15 "5" 16 "6" 17 "7" 18 "8" 19 "9" 20 "10") ///
yscale(`yschaal') ylabel(`ylabeltje') ///
xtitle("week") ytitle("`ynaam'") graphregion(fcolor(white) lcolor(white)) bgcolor(white) ///
name(RobustRushFR_`var', replace)

graph display RobustRushFR_`var'
graph save "$paperpath\RobustRushFRcoaching_`var'.png", replace
graph export "$paperpath\RobustRushFRcoaching_`var'.png", replace

}
** TABLES IN TEX ** 
local verklvar "$covPreCoaching postcoaching $covPostCoaching"

label variable postcoaching "Post-coaching"
label variable daysaftercoachingA0 "Day of first coaching"
foreach x of numlist 7(7)70 {
		local w = `x'-6
		label variable daysaftercoachingA`x' " `w' --`x' days after"
	}
label variable daysaftercoachingA70plus "$>$ 70"

foreach x of numlist 70(7)14 {
		local w = `x'-6
		label variable daysbeforecoachingA`x' " `x' --`w' days before"
	}
label variable daysbeforecoachingA70min "$<$ -70"


********************************************************************************************************************************************
***  [Table N.16: Dynamic Treatment Effects In-Person Coaching on Driving Performance – Rush Hours Excluded as Control Variable ]
***  [Table X: Time Invariant Effect In-Person Coaching on Driving Performance]
********************************************************************************************************************************************
** a. Fuel Economy + Acceleration [TWFE]
*****************************************************************************
esttab mfueleconomyLpKM1 mfueleconomyLpKM2 mfueleconomyLpKM3  macceleratie1 macceleratie2 macceleratie3 using "$paperpath/TABRobustRushFRFuelAccCoaching.tex", replace f ///
keep(`verklvar') ///
label booktabs b(3) p(3) eqlabels(none) collabels(none) mlabels(none) ///
starlevels($^{*}$ 0.10 $^{**}$ 0.05 $^{***}$ 0.01) ///
cells(b(star  fmt(%9.3f) ) se(par fmt(%9.3f))) ///
stats(N controls driverfe dayfe busdayfe, fmt(%9.0f) labels("Number of trip-level observations" "Controls" "Driver fixed effects" "Day fixed effects" "Bus type $\times$ day fixed effects")) ///
varlabels(_cons Constant) ///
prehead("\tabcolsep=0.25cm" "\begin{tabular}{l*{@M}{C{2.0cm}}}\hline\hline" "Dependent variable: &\multicolumn{3}{c}{\textbf{Fuel Economy}}&\multicolumn{3}{c}{\textbf{Acceleration}} \\" "\cline{2-4}\cline{5-7}") posthead(\hline) ///
prefoot(\hline) postfoot("\hline" "\end{tabular}")

*****************************************************************************
** b. Braking and cornering [TWFE]
*****************************************************************************
esttab mrem1 mrem2 mrem3 mbochten1 mbochten2 mbochten3  using "$paperpath/TABRobustRushFRBrakingCornCoaching.tex", replace f ///
keep(`verklvar') ///
label booktabs b(3) p(3) eqlabels(none) collabels(none) mlabels(none) ///
starlevels($^{*}$ 0.10 $^{**}$ 0.05 $^{***}$ 0.01) ///
cells(b(star  fmt(%9.3f) ) se(par fmt(%9.3f))) ///
stats(N controls driverfe dayfe busdayfe, fmt(%9.0f) labels("Number of trip-level observations" "Controls" "Driver fixed effects" "Day fixed effects" "Bus type $\times$ day fixed effects")) ///
varlabels(_cons Constant) ///
prehead("\tabcolsep=0.25cm" "\begin{tabular}{l*{@M}{C{2.0cm}}}\hline\hline" "Dependent variable: &\multicolumn{3}{c}{\textbf{Braking}}&\multicolumn{3}{c}{\textbf{Cornering}} \\" "\cline{2-4}\cline{5-7}") posthead(\hline) ///
prefoot(\hline) postfoot("\hline" "\end{tabular}")

eststo clear


*****************************************************************************
***  [FIGURES X.X-X.X: Temporal Effects In-Person Coaching at Coach Level: Fuel Economy and ABC]
*****************************************************************************
local eco_nr "939 1404 519 1286 1610 531"
local abcd "acceleratie rem bochten fueleconomyLpKM"

tab eco_coach_nr_rug if  coachdatum_1 <=date("30-4-2016", "DMY")
tab eco_coach_nr_rug if  coachdatum_1 <=date("30-4-2016", "DMY") & dep_fueleconomyLpKM~=.
tab eco_coach_nr_rug if  coachdatum_1 <=date("30-4-2016", "DMY") & dep_acceleratie~=.
tab eco_coach_nr_rug if  coachdatum_1 <=date("30-4-2016", "DMY") & dep_rem~=.
tab eco_coach_nr_rug if  coachdatum_1 <=date("30-4-2016", "DMY") & dep_bochten~=.

foreach coachnr of local eco_nr {
	local i = 0
	foreach var of local abcd {
		local i = `i' + 1
		if `i'<4 {
		replace selectie=regobsabc 
		}
		if `i'==4 {
		replace selectie=regobsfuel 
		}
		if `i'==1 { 
			local ynaam  "Difference in number of events per 10km" 
			local yschaal "r(-2 2)" 
			local ylabeltje "-2 -1 0 1 2"
			replace selectie=regobsabc 
 		}
		else if `i'==2 { 
			local ynaam  "Change in number of events per 10km" 
			local yschaal "r(-0.5 0.5)" 
			local ylabeltje "-0.50 -0.25 0 0.25 0.50"
			replace selectie=regobsabc 
		}
		else if `i'==3 { 
			local ynaam  "Change in number of events per 10km" 
			local yschaal "r(-0.8 0.2)" 
			local ylabeltje "-0.8 -0.6 -0.4 -0.2 0 0.2"
			replace selectie=regobsabc 
		}
		else if `i'==4 { 
			local ynaam  "Change in fuel economy (liters/100km)" 
			local yschaal "r(-1 0.5)" 
			local ylabeltje "-1 -0.5 0 0.5"
			replace selectie=regobsfuel 
		}
		xtreg dep_`var' $covPreCoaching $covPostCoaching $covBusType $covPassengers $covEnvironm  i.bustypes i.datum i.bustypes#i.datum if selectie==1 & (eco_coach_nr_rug==`coachnr' | (coachdatum_1 == . | coachdatum_1 >date("30-4-2016", "DMY"))), fe cluster(chauf_nr_rug)
			estimates store m`i'
			 *  Test lags = 0
			test $covPreCoaching 
			* Test leads = 0
			test $covPostCoaching 
		coefplot (m`i'), keep(daysbefore* daysafter*) drop(daysafter*plus daysbefore*min) vertical yline(0) xlabel("") xtick(#20)  xlabel(1 "-10" 2 "-9" 3 "-8" 4 "-7" 5 "-6" 6 "-5" 7 "-4"  8 "-3"  9 "-2" 10 "0" 11 "1" 12 "2" 13 "3" 14 "4" 15 "5" 16 "6" 17 "7" 18 "8" 19 "9" 20 "10") ///
		yscale(`yschaal') ylabel(`ylabeltje') ///
		xtitle("week") ytitle("`ynaam'") graphregion(fcolor(white) lcolor(white)) bgcolor(white) ///
		name(RR_`var'Coach`coachnr', replace)
			graph display RR_`var'Coach`coachnr'
			graph save "$paperpath\RR_`var'Coach`coachnr'.png", replace
			graph export "$paperpath\RR_`var'Coach`coachnr'.png", replace
	}
}


graph close

log close
